package com.zeng.controller;

import com.zeng.entity.Logsinfo;
import com.zeng.entity.Result;
import com.zeng.entity.Vicodeinfo;
import com.zeng.service.LogsinfoService;
import com.zeng.service.VicodeinfoService;
import com.zeng.utils.EmailUtils;
import com.zeng.utils.getUserIp;
import com.zeng.utils.TimeUtils;
import com.zeng.utils.ViCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * (Vicodeinfo)表控制层
 *
 * @author makejava
 * @since 2021-03-23 14:50:14
 */
@RestController
@RequestMapping("vicodeinfo")
public class VicodeinfoController {
    /**
     * 服务对象
     */
    @Resource
    private VicodeinfoService vicodeinfoService;
    @Autowired
    private EmailUtils emailUtils;

    @Resource
    private LogsinfoService logsinfoService;


    @GetMapping("getCode")
    public Result selectA(String usermail, HttpServletRequest request) {
        //定位IP
        String userip = new getUserIp().getIp(request);
        try{
            Vicodeinfo vicodeinfo1 = vicodeinfoService.checkViCode(usermail);
            String vicode = ViCodeUtils.getViCode();
            emailUtils.send(usermail, vicode);
            if (vicodeinfo1 == null) {
                vicodeinfo1 = new Vicodeinfo();
                vicodeinfo1.setUsermail(usermail);
                vicodeinfo1.setVicode(vicode);
                vicodeinfo1.setCreatetime(TimeUtils.NowTimeN());
                vicodeinfoService.insert(vicodeinfo1);
            } else {
                vicodeinfo1.setVicode(vicode);
                vicodeinfo1.setCreatetime(TimeUtils.NowTimeN());
                vicodeinfoService.update(vicodeinfo1);
            }
            //写日志
            //(String operator, Date createtime, String createip, String details, String note)
            logsinfoService.insert(new Logsinfo(usermail, TimeUtils.NowTimeN(), userip, "验证码", "发送成功"));
            return Result.success("验证码发送成功");
        } catch (Exception e) {
            System.out.println("-----------------------------------------------");
            System.out.println("验证码失败日志："+e);
            System.out.println("-----------------------------------------------");
            //写日志
            //(String operator, Date createtime, String createip, String details, String note)
            logsinfoService.insert(new Logsinfo(usermail, TimeUtils.NowTimeN(), userip, "验证码", "发送失败"));
            return Result.error("验证码发送失败");
        }
  }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Vicodeinfo selectOne(Integer id) {
        return this.vicodeinfoService.queryById(id);
    }

}
